<?php
class JYDate{
	//取该年份第一个周一的日期
	private function _getFirstMonday($AYear){
		if ($AYear === NULL) {
			$AYear = date ( 'Y' );
		}

		$week = date ( 'N', mktime ( 0, 0, 0, 1, 1, $AYear ) );
		$d = 7-$week+2;
		return array('m' => 1, 'd' => $d, 'Y' => $AYear );
	}
	
	/*取日期所在的周编号
	 * @param string $sDate 日期，默认为今天
	 * result string 年份+周数
	 */
	public function toWeek($sDate = '') {
		if ($sDate == '') {
			$sDate = date('Y-m-d');
		}
	
		$year = substr($sDate, 0, 4);
		$month = substr($sDate, 5, 2);
		$date = substr($sDate, 8, 2);
	
		$first_monday = self::_getFirstMonday($year);
	
		if ($first_monday['m'] == $month and $first_monday['d'] > $date) {
			// 属于上一年的最后一周
			return ($year - 1) . strftime('%W', mktime(0, 0, 0, 12, 31, $year - 1));
		} else {
			// 正常日期
			return $year . strftime('%W', mktime(0, 0, 0, $month, $date, $year));
		}
	}
	
	/*取周编号的信息
	 *@param string $AYearWeek 年份+周数,如201102表示2011年第2周
	 *return array 如:array('start'=>该周第一天日期,'end'=>该周最后一天日期,'days'=>该周日期数组) 
	 */
	public function getWeekInfo($AYearWeek = null) {
		if ($AYearWeek == null) {			
			$AYearWeek = self::toWeek();
		}
		$year = substr ( $AYearWeek, 0, 4 );
		$week_number = substr ( $AYearWeek, 4 );
				
		$first_monday = self::_getFirstMonday($year);
	
		$monday = date('Y-m-d', mktime(0, 0, 0, $first_monday['m'], $first_monday['d'] + 7 * ($week_number - 1), $first_monday['Y']));
	
		// 检测$week_number是否是在该年份中
		$year_of_monday = substr($monday, 0, 4);
		if ($first_monday['Y'] != $year_of_monday) {
			JYTools::error('第 ' . $week_number . ' 周超过年份 ' . $first_monday['Y'] . ' 的范围');
		}
	
		$days[0] = $monday;
		for ($i = 1; $i < 7; $i++) {
			$after_days = 7 * ($week_number - 1) + $i;
			$days[$i] = date('Y-m-d', mktime(0, 0, 0, $first_monday['m'], $first_monday['d'] + $after_days, $first_monday['Y']));
		}
	
		return array ("start" => $days[0], // 如“2009-03-14”的格式
					"end" => $days[6], 
					"days" => $days );
	}
	/*取月份信息
	 * 
	 */
	function getMonthInfo($mth=null){
		if(!$mth) $mth = date('Ym');
		$y = substr($mth,0,4);
		$m = substr($mth,-2);

		$mths['end'] = date('Y-m-d',mktime(0,0,0,$m+1,0,$y));
		$mths['start'] = date('Y-m-d',mktime(0,0,0,$m,1,$y));
		$i = 1;
		while($date<$mths['end']){
			$time = mktime(0,0,0,$m,$i++,$y);
			$date = date('Y-m-d',$time);
			$mths['days'] = $date;
			$mths['weeks'][date('N',$time)][] = $date;
			$mths['calendar'][self::toWeek($date)][] = $date;
		}
		//sort($mths['weeks']);
	//	sort($mths['calendar']);
		
		return $mths;
	}
}